﻿using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using IotWeek3Day17.EFCore;
using IotWeek3Day17.Models;
using IotWeek3Day17.Models.Dto;

using Microsoft.AspNetCore.Hosting;
using System.IO;

using Microsoft.Extensions.Logging; //引用日志功能

namespace IotWeek3Day17.WebApi.Controllers
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class ProductController : ControllerBase
    {
        private readonly ProDbContext _dbContext;
        private readonly ILogger<ProductController> _logger;

        public ProductController(ProDbContext dbContext, ILogger<ProductController> logger) //构造函数 依赖注入
        {
            _dbContext = dbContext;
            _logger = logger;
        }

        [HttpGet]
        public IActionResult GetList(int pageIndex=1, int pageSize=2, string proName="", int tid=0 /*查询条件*/)
        {
            //测试一下NLog，输出一句日志
            //_logger.LogInformation("用户访问了 获取商品接口，普通信息");
            //_logger.LogDebug("用户访问了 获取商品接口，调试信息");
            //_logger.LogError("用户访问了 获取商品接口,发生了错误");

            var query = from a in _dbContext.Products
                        join b in _dbContext.ProductTypes on a.TId equals b.TId
                        where a.IsDeleted == false //只查询 未删除的数据（逻辑删除）
                        orderby a.PId
                        select new ProductDto
                        {
                            Name = a.Name,
                            PicUrl = a.PicUrl,
                            PId = a.PId,
                            Price = a.Price,
                            Status = a.Status,
                            TId = b.TId,
                            TName =b.Name,
                            IsDeleted = a.IsDeleted, //逻辑删除
                            CTime = a.CTime,
                            CUser = a.CUser,
                            MTime = a.MTime,
                            MUser = a.MUser
                        };
            if (!string.IsNullOrEmpty(proName))
            {
                query = query.Where(x => x.Name.Contains(proName));
            }
            if (tid != 0)
            {
                query = query.Where(x => x.TId == tid);
            }

            int totalCount = query.Count();
            var data = query.Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList();

            //不返回总页数
            return Ok(new { totalCount, data });
        }

        //[FromServices]特性的作用是，进行方法注入。注入了IWebHostEnvironment服务，作用是：获取服务器的路径
        [HttpPost]
        public IActionResult UploadImg(IFormFile file, [FromServices] IWebHostEnvironment environment)
        {
            //1.判断文件是否为空
            if (file.Length == 0)
            {
                return Ok(new { msg = "文件不能为空", result = -1 });
            }

            try
            {
                //2.拼接保存路径
                string fileName = file.FileName;
                string filePath = environment.WebRootPath + @"\Upload\" + fileName;

                using FileStream fileStream = new FileStream(filePath, FileMode.Create);

                file.CopyTo(fileStream); //把上传的文件拷贝到文件流

                fileStream.Flush();  //关闭文件流

                _logger.LogInformation("文件上传成功:" + fileName);

                return Ok(new { msg = "上传成功", path = @"/Upload/" + fileName, result = 1 });
            }
            catch (Exception e)
            {
                _logger.LogError("发生异常：" + e.Message);
                return Ok(new { msg = "发生异常："+ e.Message, result = -2 });
            }
        }

        /// <summary>
        // 添加商品
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost]
        public IActionResult Add(Product input)
        {
            if (ModelState.IsValid)
            {
                input.CUser = "管理员1"; //创建人
                input.CTime = DateTime.Now; //创建时间

                _dbContext.Products.Add(input);
                int result = _dbContext.SaveChanges();

                return Ok(new { msg = result > 0 ? "添加成功" : "添加失败", result });
            }

            return Ok(new { msg = "模型数据无效", result = -1 });
        }

        /// <summary>
        /// 大修改
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost]
        public IActionResult Upt(Product input)
        {
            if (ModelState.IsValid)
            {
                input.MUser = "管理员2"; //创建人
                input.MTime = DateTime.Now; //创建时间

                _dbContext.Products.Update(input);
                int result = _dbContext.SaveChanges();

                return Ok(new { msg = result > 0 ? "修改成功" : "修改失败", result });
            }

            return Ok(new { msg = "模型数据无效", result = -1 });
        }

        /// <summary>
        /// 逻辑删除（小修改）
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost]
        public IActionResult Del(string ids)
        {
            if (!string.IsNullOrEmpty(ids))
            {
                string[] aIds = ids.Split(',');
                //查询所有ids的商品
                List<Product> products = _dbContext.Products.Where(x => aIds.Contains(x.PId.ToString())).ToList();
                foreach (var item in products)
                {
                    item.IsDeleted = true; //逻辑删除
                }
                int result = _dbContext.SaveChanges();

                return Ok(new { msg = result > 0 ? "修改成功" : "修改失败", result });
            }

            return Ok(new { msg = "参数无效", result = -1 });
        }

        /// <summary>
        /// 上下架状态 切换（小修改）
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost]
        public IActionResult UptStatus(int id, int status)
        {
            Product p = _dbContext.Products.Find(id); //主键查询
            p.Status = (ProductStatus)status; //强转成枚举

            int result = _dbContext.SaveChanges();

            return Ok(new { msg = result > 0 ? "修改成功" : "修改失败", result });
        }

        /// <summary>
        /// 获取商品类型（用于下拉绑定）
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public IActionResult GetTypes()
        {
            return Ok(_dbContext.ProductTypes.ToList());
        }

        /// <summary>
        /// 获取单条商品（用于修改返填）
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet]
        public IActionResult GetProduct(int id)
        {
            Product p = _dbContext.Products.Find(id); //主键查询

            return Ok(p);
        }
    }
}
